package com.runner.track;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.runner.entity.CollisionEntity;
import com.runner.player.Player;
import com.runner.utility.Locator;

public class Coin extends CollisionEntity {

	private static final float MAGNET_SPEED = 280 * RELATIVE_SPEED;
	protected Animation animation;
	protected TextureRegion[] frames;
	protected TextureRegion currentFrame;
	protected float stateTime;
	private Player player;
	private boolean followPlayer;
	public static final float SCALE = 0.5f;

	public Coin(Vector2 position) {
		super(1, 4, position, TYPE.COIN, COIN_PATH, false, true, false, SCALE);
		// animation
		int cols = 1;
		int rows = 4;
		Texture sheet = this.getSprite().getTexture();
		TextureRegion[][] tmp = TextureRegion.split(sheet, sheet.getWidth() / cols, sheet.getHeight() / rows);
		frames = new TextureRegion[cols * rows];
		int index = 0;
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				frames[index++] = tmp[i][j];
			}
		}
		float animTime = 0.25f / (float) (cols * rows);
		animation = new Animation(animTime, frames);
		stateTime = 0f;
		currentFrame = animation.getKeyFrame(stateTime, true);
	}

	@Override
	public void render(SpriteBatch sb) {
		if (currentFrame != null) {
			super.render(sb, currentFrame);
		}

	}

	@Override
	public void update(float delta) {
		super.update(delta);
		stateTime += delta;
		currentFrame = animation.getKeyFrame(stateTime, true);
		// if the coin hasnt been magnetized go normal speed, else follow the
		// player
		if (!followPlayer) {
			physics.getBody().setLinearVelocity(-Block.SPEED * Locator.getXGameSpeed() * delta, 0);
		} else {
			Vector2 vel = new Vector2(player.getPhysics().getBody().getPosition().sub(this.getPhysics().getBody().getPosition()));
			vel.nor();
			this.getPhysics().getBody().setLinearVelocity(vel.scl(delta * MAGNET_SPEED));
		}
		// delete the coin if its off the screen or if its been collected by
		// player
		if (!exists || physics.getBody().getPosition().x < -COIN_WIDTH * Locator.getxSpriteScale()) {
			delete();
			exists = false;
		}
	}

	public void followPlayer(Player player) {
		this.player = player;
		followPlayer = true;
	}

	@Override
	public void collide(CollisionEntity otherBody) {
		if (otherBody.getPhysics().getType().equals(TYPE.PLAYER)) {
			exists = false;
		}

	}

}
